package gui;

import gui.AddUser;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JPasswordField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

import java.awt.Font;
import javax.swing.JButton;

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import logic.CRUDUsers;
import logic.Teacher;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * Tela inicial que sera exibida ao usuario toda vez que ele logar no sistema.
 * @author PauloNote
 *
 */
public class LoginScreen {

	private JFrame frame;
	private JLabel emailLbl;
	private JTextField emailField;
	private JPasswordField passwordField;
	private JButton btnCriarNovoUsurio;
	private JLabel lblCoolrent;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					LoginScreen window = new LoginScreen();
					window.frame.setVisible(true);
					
					
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public LoginScreen() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		try {
		    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
		        if ("Nimbus".equals(info.getName())) {
		            UIManager.setLookAndFeel(info.getClassName());
		            break;
		        }
		    }
		} catch (Exception e) {
		    // If Nimbus is not available, you can set the GUI to another look and feel.
		}
		
		frame = new JFrame();
		frame.setResizable(false);
		frame.setFont(new Font("Tahoma", Font.PLAIN, 12));
		
		frame.setBounds(100, 100, 280, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		emailLbl = new JLabel("Email");
		emailLbl.setFont(new Font("Tahoma", Font.BOLD, 14));
		emailLbl.setBounds(34, 102, 64, 14);
	
		frame.getContentPane().add(emailLbl);
		
		emailField = new JTextField();
		emailField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				if (KeyEvent.VK_ENTER == arg0.getKeyCode()){
					doLogin();
				}
			}
		});
		emailField.setToolTipText("Seu email cadastrado no sistema.");
		emailField.setBounds(83, 97, 169, 30);
		frame.getContentPane().add(emailField);
		emailField.setColumns(10);
		
		JLabel lblSenha = new JLabel("Senha");
		lblSenha.setFont(new Font("Tahoma", Font.BOLD, 14));
		lblSenha.setBounds(34, 132, 70, 14);
		frame.getContentPane().add(lblSenha);
		
		passwordField = new JPasswordField();
		passwordField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				if (KeyEvent.VK_ENTER == arg0.getKeyCode()){
					doLogin();
				}
			}
		});
		passwordField.setToolTipText("Sua senha cadastrada ao sistema.");
		passwordField.setBounds(83, 125, 169, 30);
		frame.getContentPane().add(passwordField);
		
		JButton btnLogar = new JButton("Logar");
		btnLogar.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				doLogin();
			}
		});
		
		btnLogar.setFont(new Font("Tahoma", Font.PLAIN, 12));
		btnLogar.setToolTipText("Clique para ter acesso ao sistema. ");
		btnLogar.setBounds(34, 163, 218, 28);
		frame.getContentPane().add(btnLogar);
		
		JButton btnRedefinirSenha = new JButton("Lembrete de senha");
		btnRedefinirSenha.setFont(new Font("Tahoma", Font.PLAIN, 12));
		btnRedefinirSenha.setToolTipText("Clique para redefinir a sua senha");
		btnRedefinirSenha.setBounds(34, 195, 218, 28);
		btnRedefinirSenha.addMouseListener(new MouseAdapter() {
			
			@Override
			public void mouseClicked(MouseEvent arg0) {
				String email = JOptionPane.showInputDialog(null, "Email: ");
				int sendReminder = JOptionPane.showConfirmDialog(null, "Tem certeza que deseja mandar um email para: " + email.trim());
				if (sendReminder == JOptionPane.OK_OPTION){
					try {
						if (CRUDUsers.retrievePassword(email.trim())){
							JOptionPane.showMessageDialog(null, "Email com lembrete de senha enviado para o seu email");
						} else {
							JOptionPane.showMessageDialog(null, "Algo aconteceu e sua mensagem não pode ser enviada");
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						JOptionPane.showMessageDialog(null, "Erro: " + e.getMessage());
					}
				}
				
			}
		});
		frame.getContentPane().add(btnRedefinirSenha);
		
		btnCriarNovoUsurio = new JButton("Criar novo usuário");
		btnCriarNovoUsurio.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				final AddUser au = new AddUser();
				au.setVisible(true);
				au.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);				
			}
		});
		btnCriarNovoUsurio.setFont(new Font("Tahoma", Font.PLAIN, 12));
		btnCriarNovoUsurio.setToolTipText("Clique para criar novo usuário.");
		btnCriarNovoUsurio.setBounds(34, 228, 218, 28);
		frame.getContentPane().add(btnCriarNovoUsurio);
		
		lblCoolrent = new JLabel("CoolRent");
		lblCoolrent.setToolTipText("Biblioteca Descentralizada.");
		lblCoolrent.setFont(new Font("Segoe UI", Font.PLAIN, 40));
		lblCoolrent.setHorizontalAlignment(SwingConstants.CENTER);
		lblCoolrent.setBounds(18, 6, 234, 84);
		frame.getContentPane().add(lblCoolrent);
		}

	protected void doLogin() {
		try {
			Teacher t = (Teacher) CRUDUsers.getUser(emailField.getText().trim());
			System.out.println(t);
			if (t.getPassword().equals(new String(passwordField.getPassword()))){
				MainScreen ms = new MainScreen(t);
				ms.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				ms.setVisible(true);
				frame.setVisible(false);
			} else {
				JOptionPane.showMessageDialog(null, "Senha inválida!");
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Login não pode ser realizado. Erro: " + e.getMessage());
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
	}
}
